package ServerPackge;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor2 extends Thread {
    private Socket socket;
    private Server server;

    public RequestProcessor2(Socket socket,Server server) {
        this.socket = socket;
        this.server = server;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 获取指定的Servlet
            HttpServlet httpServlet = getHttpServlet(request);

            if(null == httpServlet){
                // servlet不存在，处理静态页面
                response.outputHtml(request.getUrl());
            }else{
                httpServlet.service(request,response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HttpServlet getHttpServlet(Request request){
        HttpServlet businessServlet = null;
        // 获取所有的Mapper内容
        Map<String, Mapper> serviceMap = server.getServiceMap();
        for (String key : serviceMap.keySet()) {
            String hostName = request.getHost();

            // Host集合
            Map<String, Host> hostMap = serviceMap.get(key).getHostMap();

            Host host = hostMap.get(hostName);

            if(null != host){

                // Context集合
                Map<String, Context> contextMap = host.getContextMap();

                // 处理url
                String url = request.getUrl();
                String []urlPattern = url.split("/");
                String contextName = urlPattern[1];
                String servletStr = "/";
                if(urlPattern.length > 2){
                    servletStr += urlPattern[2];
                }

                Context context = contextMap.get(contextName);
                if(null != context){
                    Map<String, HttpServlet> servletMap = context.getServletMap();
                    businessServlet = servletMap.get(servletStr);
                }

            }
        }

        return businessServlet;
    }
}
